package com.duan.laugh.mp.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duan.laugh.common.core.util.R;
import com.duan.laugh.mp.api.pojo.entity.MpAccount;
import com.duan.laugh.mp.config.WxMpConfiguration;
import com.duan.laugh.mp.service.IMpAccountService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


/**
 * 公众号账户
 *
 * @author duanjw
 * @date 2019-03-26 22:07:53
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wxaccount")
public class MpAccountController {
    private final WxMpConfiguration wxMpConfiguration;
    private final IMpAccountService IMpAccountService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param wxAccount 公众号账户
     * @return
     */
    @GetMapping("/page")
    public R getWxAccountPage(Page page, MpAccount wxAccount) {
        return R.ok(IMpAccountService.page(page, Wrappers.query(wxAccount)));
    }


    /**
     * 通过id查询公众号账户
     *
     * @param id id
     * @return R
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(IMpAccountService.getById(id));
    }

    /**
     * 新增公众号账户
     *
     * @param wxAccount 公众号账户
     * @return R
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('mp_wxaccount_add')")
    public R save(@RequestBody MpAccount wxAccount) {
        IMpAccountService.save(wxAccount);
        wxMpConfiguration.initServices();
        return R.ok();
    }

    /**
     * 修改公众号账户
     *
     * @param wxAccount 公众号账户
     * @return R
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('mp_wxaccount_edit')")
    public R updateById(@RequestBody MpAccount wxAccount) {
        IMpAccountService.updateById(wxAccount);
        wxMpConfiguration.initServices();
        return R.ok();
    }

    /**
     * 通过id删除公众号账户
     *
     * @param id id
     * @return R
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('mp_wxaccount_del')")
    public R removeById(@PathVariable Integer id) {
        IMpAccountService.removeById(id);
        wxMpConfiguration.initServices();
        return R.ok();
    }

    /**
     * 生成公众号二维码
     *
     * @param appId
     * @return
     */
    @PostMapping("/qr/{appId}")
    public R qr(@PathVariable String appId) {
        return IMpAccountService.generateQr(appId);
    }

    /**
     * 获取公众号列表
     *
     * @return
     */
    @GetMapping("/list")
    public R list() {
        return R.ok(IMpAccountService.list());
    }

    /**
     * 获取公众号接口数据
     *
     * @param appId    公众号
     * @param interval 时间间隔
     * @return
     */
    @GetMapping("/statistics")
    public R statistics(String appId, String interval) {
        return IMpAccountService.statistics(appId, interval);
    }
}
